package com.hnl.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.core.connection.ConnectionManager;
import com.hnl.core.connection.ConnectionManagerFactory;
import com.hnl.to.RoleFunction;

public class DBRoleFunctionDAO implements RoleFunctionDAO {
	public static final Logger LOG = LoggerFactory
			.getLogger(DBRoleFunctionDAO.class);

	private PreparedStatement saveStmt;
	private PreparedStatement updateStmt;
	private PreparedStatement delStmt;

	protected DBRoleFunctionDAO() throws SQLException {
		// Empty protected constructor to avoid unnecessary initialization
	}

	public RoleFunction saveRoleFunction(RoleFunction roleFunction) {
		ConnectionManager dbConnMgr = ConnectionManagerFactory
				.getConnectionManager(ConnectionManagerFactory.HNL);
		Connection conn = dbConnMgr.getConnection();

		try {
			saveStmt = conn.prepareStatement(
					"INSERT INTO ROLE_FUNCTION (role_ID, function_ID) "
							+ "VALUES (?,?)",
					PreparedStatement.RETURN_GENERATED_KEYS);
			saveStmt.setInt(1, roleFunction.getRoleID());
			saveStmt.setInt(2, roleFunction.getFunctionID());
			saveStmt.executeUpdate();

			ResultSet rs = saveStmt.getGeneratedKeys();
			if (rs.next()) {
				roleFunction.setFunctionID(rs.getInt(1));
			}
			rs.close();
			saveStmt.close();
		} catch (SQLException e) {
			LOG.error("Error saving RoleFunction.", e);
		} finally {
			dbConnMgr.releaseConnection(conn);
		}
		return roleFunction;
	}

	public void updateRoleFunction(RoleFunction roleFunction) {
		ConnectionManager dbConnMgr = ConnectionManagerFactory
				.getConnectionManager(ConnectionManagerFactory.HNL);
		Connection conn = dbConnMgr.getConnection();

		try {
			updateStmt = conn
					.prepareStatement("UPDATE ROLE_FUNCTION SET role_ID=?, function_ID=?"
							+ "WHERE role_function_ID=?");
			updateStmt.setInt(1, roleFunction.getRoleID());
			updateStmt.setInt(2, roleFunction.getFunctionID());
			updateStmt.setInt(3, roleFunction.getRoleFunctionID());

			updateStmt.executeUpdate();
			updateStmt.close();
		} catch (SQLException e) {
			LOG.error("Error updating RoleFunction.", e);
		} finally {
			dbConnMgr.releaseConnection(conn);
		}
	}

	public void deleteRoleFunction(Integer roleFunctionID) {
		ConnectionManager dbConnMgr = ConnectionManagerFactory
				.getConnectionManager(ConnectionManagerFactory.HNL);
		Connection conn = dbConnMgr.getConnection();

		try {
			delStmt = conn.prepareStatement("DELETE FROM ROLE_FUNCTION "
					+ "WHERE role_function_ID = ?");
			delStmt.setInt(1, roleFunctionID);
			delStmt.executeUpdate();
			delStmt.close();
		} catch (SQLException e) {
			LOG.error("Error deleting RoleFunction.", e);
		} finally {
			dbConnMgr.releaseConnection(conn);
		}
	}

}
